/*
    fly配置文件
    by:wangyuda 2019.2.18
*/
//引入 fly
import Fly from "flyio/dist/npm/wx";
import store from '@/store/index';
import myModule from './myModule';
const requestKey = myModule.get("requestKey");
var fly = new Fly();

//配置请求基地址
fly.config.timeout = 20000;
//fly.config.baseURL = config.host;

/******     添加请求拦截器    ******/
fly.interceptors.request.use(function (request) {

  //加载公共参数
  var csrfToken = store.state.userInfo ? store.state.userInfo.token : '';
  request.body.token = csrfToken;
});

/******     添加响应拦截器，响应拦截器会在then/catch处理之前执行    ******/
fly.interceptors.response.use(
  (res) => {
    return res.data;
  },

  (err) => {
    
    return Promise.resolve({code: -1, msg: "连接失败！"})
  }
);



/******     封装的http函数    ******/
async function customFly (url, data, method= "post") {
  // http重复请求apikey，http响应的数据，组装后的响应数据请求
  var ajaxKey, response, newResponse = {};

  if(!url, !data) return {data: null, err: "url data 不能为空！"};

  ajaxKey = requestKey.get({url, data, method});
  // console.log("已阻止重复请求：" + ajaxKey), failCb();
  if (requestKey.has(ajaxKey)) return {data: null};

  // 将key添加进请求队列中
  requestKey.add(ajaxKey);

  //状态显示


  method = method.toLowerCase();

  

  // 调用fly请求数据
  response = await fly[method](url, data);

  // 服务器状态判断
  if(Number(response.code) === 1){ // 服务器返回成功
    newResponse.data = response.data || {};

  } else if (Number(response.code) === 408) { // 未登录
    newResponse.data = null;
    newResponse.err = '未登录';
  } else {
    newResponse.data = null;
    newResponse.err = response.msg || response.message || "请求失败！";
  }

  // 删除请求队列，防止重复提交
  requestKey.remove(ajaxKey);


  return newResponse;
  

}
/******     封装的http函数 end    ******/

export default customFly;
